<template>
  <div class="drift-bottle-app">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="wave wave-1"></div>
      <div class="wave wave-2"></div>
      <div class="wave wave-3"></div>

      <!-- 浮动装饰元素 -->
      <div class="floating-elements">
        <div class="floating-circle circle-1"></div>
        <div class="floating-circle circle-2"></div>
        <div class="floating-circle circle-3"></div>
        <div class="floating-circle circle-4"></div>
      </div>
    </div>

    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-left">
        <img src="@/assets/icons/icon_app_logo.svg" alt="运动漂流瓶" class="app-logo" />
        <h1 class="app-title">运动漂流瓶</h1>
      </div>
      <div class="header-center">
        <div class="header-actions">
          <!-- <button class="action-btn my-bottles-btn" >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2M12 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8z"
                stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
            </svg>
            我的瓶子
          </button> -->
          <button class="action-btn fish-btn" @click="fishBottle" v-if="$route.name === 'DriftBottle' && !shouldHide">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" stroke="currentColor" stroke-width="2"
                stroke-linecap="round" stroke-linejoin="round" />
            </svg>
            捞瓶子
          </button>
          <button class="action-btn throw-btn" @click="showThrowModal = true"
            v-if="$route.name === 'DriftBottle' && !shouldHide">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path d="M12 5v14M5 12h14" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
            </svg>
            扔瓶子
          </button>
        </div>
      </div>
      <div class="header-right">
        <div class="my-bottles">
          <img src="@/assets/icons/icon_my_bottles.svg" alt="我的瓶子" class="bottles-icon" />
          <span class="bottles-text">我的瓶子</span>
          <span class="bottles-count">{{ bottlesCount }}</span>
        </div>
        <img src="@/assets/icons/icon_settings.svg" alt="设置" class="settings-icon" />
      </div>
    </header>

    <div class="main-container">
      <!-- 左侧功能操作区 -->
      <aside class="left-sidebar">
        <div class="action-buttons">
          <button class="action-btn" :class="{ 'drift-btn': activeButton === 'drift-bottle' }"
            @click="setActiveButton('drift-bottle'); goToDriftBottle()">
            <img src="@/assets/icons/icon_fish_bottle.svg" alt="漂流瓶" class="btn-icon" />
            <span>漂流瓶</span>
          </button>

          <button class="action-btn" :class="{ 'drift-btn': activeButton === 'inbox' }"
            @click="setActiveButton('inbox'); router.push('/drift-bottle/received')">
            <img src="@/assets/icons/icon_inbox.svg" alt="收到的瓶子" class="btn-icon" />
            <span>收到的瓶子</span>
          </button>

          <button class="action-btn" :class="{ 'drift-btn': activeButton === 'sent' }"
            @click="setActiveButton('sent'); goToMyBottles()">
            <img src="@/assets/icons/icon_sent.svg" alt="发出的瓶子" class="btn-icon" />
            <span>发出的瓶子</span>
          </button>
        </div>
      </aside>

      <!-- 中间内容展示区 -->
      <main class="main-content">
        <!-- 子路由内容 -->
        <router-view />

        <!-- 漂流瓶列表 -->
        <div class="bottles-container" v-if="$route.name === 'DriftBottle' && !shouldHide">
          <div v-for="bottle in bottles" :key="bottle.id" class="bottle-item"
            :class="{ 'expanded': expandedBottle === bottle.id }" :style="{
              '--random-x': bottle.randomX + 'px',
              '--random-y': bottle.randomY + 'px',
              '--random-rotate': bottle.randomRotate + 'deg',
              '--distance': bottle.distance + 'km',
              '--float-amplitude': bottle.floatAmplitude + 'px',
              '--float-duration': bottle.floatDuration + 's',
              '--float-delay': bottle.floatDelay + 's',
              '--float-direction': bottle.floatDirection + 'deg',
              '--float-pattern': bottle.floatPattern,
              'top': bottle.randomTop + '%',
              'left': bottle.randomLeft + '%',
              'right': bottle.randomRight + '%',
              'animation-duration': bottle.floatDuration + 's',
              'animation-delay': bottle.floatDelay + 's'
            }" @click="toggleBottle(bottle.id)">

            <!-- 头像（初始状态） -->
            <div class="avatar-container" v-if="expandedBottle !== bottle.id"
              :class="{ 'user-bottle': bottle.isUserBottle }">
              <div class="avatar-decoration">
                <div class="decoration-ring ring-1"></div>
                <div class="decoration-ring ring-2"></div>
                <div class="decoration-ring ring-3"></div>
              </div>
              <img :src="bottle.avatar" :alt="bottle.username" class="user-avatar" />
              <div class="avatar-glow"></div>
              <div class="floating-particles">
                <div class="particle particle-1">✨</div>
                <div class="particle particle-2">⭐</div>
                <div class="particle particle-3">💫</div>
              </div>
              <!-- 用户瓶子标识 -->
              <div v-if="bottle.isUserBottle" class="user-bottle-badge">
                <span>我的</span>
              </div>
            </div>

            <!-- 展开的详细信息 -->
            <div class="bottle-details" v-if="expandedBottle == bottle.id"
              :class="{ 'user-bottle-detail': bottle.isUserBottle }">
              <div class="bottle-header">
                <img :src="bottle.avatar" :alt="bottle.username" class="detail-avatar"
                  :class="{ 'user-avatar-detail': bottle.isUserBottle }" />
                <div class="user-info">
                  <h3 class="username">
                    {{ bottle.username }}
                    <span v-if="bottle.isUserBottle" class="user-badge">我的瓶子</span>
                  </h3>
                  <span class="distance">{{ bottle.distance }}km</span>
                </div>
              </div>

              <div class="bottle-content">
                <p class="message">{{ bottle.message }}</p>
                <div class="tags">
                  <span v-for="tag in bottle.tags" :key="tag" class="tag">{{ tag }}</span>
                </div>
                <div class="meta-info">
                  <span class="time">{{ bottle.timeAgo }}</span>
                  <span class="location">{{ bottle.location }}</span>
                </div>
              </div>

              <div class="bottle-actions">
                <button class="action-button reply-btn">
                  <span class="action-icon">💬</span>
                  <span>回复</span>
                </button>
                <button class="action-button like-btn" :class="{ 'liked': bottle.isLiked }"
                  @click.stop="toggleLike(bottle.id)">
                  <span class="action-icon">{{ bottle.isLiked ? '❤️' : '🤍' }}</span>
                  {{ bottle.likes }}
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部操作栏 -->
        <div class="bottom-actions" v-if="$route.name === 'DriftBottle' && !shouldHide">
          <button class="bottom-btn refresh-btn" @click="refreshBottles" :disabled="isRefreshing">
            <div class="refresh-icon" :class="{ 'spinning': isRefreshing }">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                <path d="M1 4v6h6M23 20v-6h-6" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                  stroke-linejoin="round" />
                <path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15" stroke="currentColor"
                  stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
              </svg>
            </div>
            <span class="btn-text">{{ isRefreshing ? '刷新中...' : '刷新' }}</span>
          </button>
        </div>
      </main>

      <!-- 右侧信息统计与热门标签区 -->
      <aside class="right-sidebar">
        <div class="my-data">
          <div class="section-title">
            <img src="@/assets/icons/icon_chart.svg" alt="我的数据" class="section-icon" />
            <h2>我的数据</h2>
          </div>
          <div class="data-list">
            <div class="data-item">
              <img src="@/assets/icons/icon_sent_small.svg" alt="扔出瓶子" class="data-icon" />
              <span>扔出瓶子 23</span>
            </div>
            <div class="data-item">
              <img src="@/assets/icons/icon_fish_bottle_small.svg" alt="捞到瓶子" class="data-icon" />
              <span>捞到瓶子 45</span>
            </div>
          </div>
        </div>
      </aside>
    </div>

    <!-- 扔瓶子模态框 -->
    <div v-if="showThrowModal" class="modal-overlay" @click="showThrowModal = false">
      <div class="throw-modal" @click.stop>
        <div class="modal-header">
          <h3>🌊 扔瓶子</h3>
          <button class="close-btn" @click="showThrowModal = false">×</button>
        </div>
        <div class="modal-content">
          <div class="form-group">
            <label>标题</label>
            <input v-model="newBottleTitle" type="text" placeholder="给你的瓶子起个标题..." maxlength="20">
          </div>

          <div class="form-group">
            <label>内容 <span class="required">*</span></label>
            <textarea v-model="newBottleContent" placeholder="写下你想分享的内容..." rows="6" maxlength="500"></textarea>
            <div class="char-count">{{ newBottleContent.length }}/500</div>
          </div>

          <div class="form-group">
            <label>标签</label>
            <input v-model="newBottleTags" type="text" placeholder="用逗号分隔，如：运动,健身,跑步" maxlength="50">
          </div>

          <div class="form-group">
            <label>位置</label>
            <input v-model="newBottleLocation" type="text" placeholder="你在哪里？" maxlength="30">
          </div>

          <div class="form-group">
            <label>心情</label>
            <div class="mood-selector">
              <label class="mood-option" :class="{ active: newBottleMood === 'happy' }">
                <input v-model="newBottleMood" type="radio" value="happy">
                <span>😊 开心</span>
              </label>
              <label class="mood-option" :class="{ active: newBottleMood === 'excited' }">
                <input v-model="newBottleMood" type="radio" value="excited">
                <span>🤩 兴奋</span>
              </label>
              <label class="mood-option" :class="{ active: newBottleMood === 'peaceful' }">
                <input v-model="newBottleMood" type="radio" value="peaceful">
                <span>😌 平静</span>
              </label>
              <label class="mood-option" :class="{ active: newBottleMood === 'motivated' }">
                <input v-model="newBottleMood" type="radio" value="motivated">
                <span>💪 励志</span>
              </label>
            </div>
          </div>
        </div>
        <div class="modal-actions">
          <button class="cancel-btn" @click="showThrowModal = false" :disabled="isThrowing">取消</button>
          <button class="confirm-btn" @click="throwBottle" :disabled="isThrowing">
            <span v-if="isThrowing">扔出中...</span>
            <span v-else>🌊 扔出瓶子</span>
          </button>
        </div>
      </div>
    </div>

    <!-- 捞瓶子模态框 -->
    <div v-if="showFishModal" class="modal-overlay" @click="showFishModal = false">
      <div class="fish-modal" @click.stop>
        <div class="fish-animation" v-if="isFishing">
          <div class="fishing-rod">
            <div class="rod-line"></div>
            <div class="hook">🎣</div>
          </div>
          <div class="water-waves">
            <div class="wave"></div>
            <div class="wave"></div>
            <div class="wave"></div>
          </div>
          <p class="fishing-text">正在捞瓶子...</p>
        </div>

        <div class="caught-bottle" v-if="caughtBottle && !isFishing">
          <div class="bottle-animation">
            <div class="bottle-icon">🍶</div>
            <div class="sparkles">
              <span class="sparkle">✨</span>
              <span class="sparkle">⭐</span>
              <span class="sparkle">💫</span>
            </div>
          </div>
          <h3>恭喜！你捞到了一个瓶子</h3>
          <div class="bottle-content-card">
            <div class="bottle-header">
              <img :src="caughtBottle.avatar" :alt="caughtBottle.username" class="caught-avatar" />
              <div class="caught-info">
                <h4>{{ caughtBottle.username }}</h4>
                <span class="caught-distance">{{ caughtBottle.distance }}km</span>
              </div>
            </div>
            <p class="caught-message">{{ caughtBottle.message }}</p>
            <div class="caught-tags">
              <span v-for="tag in caughtBottle.tags" :key="tag" class="caught-tag">{{ tag }}</span>
            </div>
            <div class="caught-meta">
              <span>{{ caughtBottle.timeAgo }}</span>
              <span>来自 {{ caughtBottle.location }}</span>
            </div>
          </div>
          <div class="fish-modal-actions">
            <button class="reply-btn" @click="replyToBottle">回复</button>
            <button class="like-btn" @click="likeBottle">点赞 ❤️</button>
            <button class="close-btn" @click="closeFishModal">关闭</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 自定义提示框 -->
    <div v-if="showToast" class="toast-container">
      <div class="toast" :class="`toast-${toastType}`">
        <div class="toast-icon">
          <span v-if="toastType === 'success'">✅</span>
          <span v-else-if="toastType === 'error'">❌</span>
          <span v-else-if="toastType === 'warning'">⚠️</span>
          <span v-else-if="toastType === 'info'">ℹ️</span>
        </div>
        <div class="toast-message">{{ toastMessage }}</div>
        <button class="toast-close" @click="showToast = false">×</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

// 使用本地数据存储
const sentBottles = ref([])
const receivedBottles = ref([])

// 导入头像图片
import avatarChenyundong from '@/assets/images/avatar_chenyundong.png'
import avatarLiyujia from '@/assets/images/avatar_liyujia.png'
import avatarWangqixing from '@/assets/images/avatar_wangqixing.png'
import avatarZhangjianshen from '@/assets/images/avatar_zhangjianshen.png'
import avatarZhaoyouyong from '@/assets/images/avatar_zhaoyouyong.png'
import avatarLinpaobu from '@/assets/images/avatar_linpaobu.png'
import avatarSunquanji from '@/assets/images/avatar_sunquanji.png'

// 捞瓶子和扔瓶子相关的响应式数据
const showThrowModal = ref(false)
const showFishModal = ref(false)
const newBottleContent = ref('')
const newBottleTitle = ref('')
const newBottleTags = ref('')
const newBottleLocation = ref('')
const newBottleMood = ref('happy')
const isThrowing = ref(false)
const isFishing = ref(false)
const caughtBottle = ref(null)

// 提示框相关
const showToast = ref(false)
const toastMessage = ref('')
const toastType = ref('success') // success, error, warning, info

// 刷新状态
const isRefreshing = ref(false)

// 漂流瓶相关的响应式数据
const expandedBottle = ref(null)

// 当前激活的按钮
const activeButton = ref('drift-bottle')

// 检查是否应该隐藏元素（当路由包含my-bottles时）
const shouldHide = computed(() => {
  return route.path.includes('my-bottles')
})

// 动态获取发出的瓶子数量
const bottlesCount = computed(() => {
  return sentBottles.value.length
})

// 动态获取数据统计
const myDataStats = computed(() => {
  const totalSent = sentBottles.value.length
  const totalReplies = sentBottles.value.reduce((sum, bottle) => sum + bottle.replies.length, 0)
  const totalLikes = sentBottles.value.reduce((sum, bottle) => sum + (bottle.likes || 0), 0)

  return {
    sent: totalSent,
    replies: totalReplies,
    likes: totalLikes
  }
})


// 模拟数据
const bottles = ref([])

// 检查位置是否重叠
const isPositionOverlapping = (newPos, existingPositions, minDistance = 18) => {
  return existingPositions.some(pos => {
    const distance = Math.sqrt(
      Math.pow(newPos.top - pos.top, 2) +
      Math.pow(newPos.left - pos.left, 2)
    )
    return distance < minDistance
  })
}

// 生成不重叠的随机位置
const generateNonOverlappingPosition = (existingPositions, minDistance = 18) => {
  let attempts = 0
  let newPos

  do {
    newPos = {
      top: Math.random() * 60 + 20, // 20% 到 80%，为75px的瓶子留出足够空间
      left: Math.random() * 70 + 15, // 15% 到 85%，为75px的瓶子留出足够空间
    }
    attempts++
  } while (isPositionOverlapping(newPos, existingPositions, minDistance) && attempts < 200)

  // 如果尝试次数过多，使用网格化位置
  if (attempts >= 200) {
    return generateGridPosition(existingPositions, minDistance)
  }

  return newPos
}

// 网格化位置生成（备用方案）
const generateGridPosition = (existingPositions, minDistance = 20) => {
  const gridSize = minDistance
  const rows = Math.floor(75 / gridSize)
  const cols = Math.floor(75 / gridSize)

  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      const pos = {
        top: 20 + row * gridSize, // 从20%开始，为瓶子留出空间
        left: 15 + col * gridSize // 从15%开始，为瓶子留出空间
      }

      if (!isPositionOverlapping(pos, existingPositions, minDistance)) {
        return pos
      }
    }
  }

  // 如果网格也满了，返回一个随机位置
  return {
    top: Math.random() * 60 + 20, // 20% 到 80%
    left: Math.random() * 70 + 15 // 15% 到 85%
  }
}

// 生成随机位置和数据
const generateRandomBottles = () => {
  const names = [
    '陈运动', '李瑜伽', '王骑行', '张健身', '赵游泳', '林跑步', '孙拳击', '周篮球', '吴足球', '郑网球',
    '黄滑板', '徐攀岩', '刘游泳', '陈健身', '李跑步', '王瑜伽', '张骑行', '赵拳击', '林篮球', '孙足球',
    '周网球', '吴滑板', '郑攀岩', '黄游泳', '徐健身', '刘跑步', '陈瑜伽', '李骑行', '王拳击', '张篮球',
    '赵足球', '林网球', '孙滑板', '周攀岩', '吴游泳', '郑健身', '黄跑步', '徐瑜伽', '刘骑行', '陈拳击'
  ]
  const messages = [
    '坚持晨跑100天,寻找同行者!',
    '想找人一起练习瑜伽,互相监督!',
    '周末骑行约伴,环城线路!',
    '寻找健身房搭档,互相指导!',
    '寻找周末游泳伙伴,一起提升技术!',
    '准备秋季马拉松,找陪练!',
    '想找人一起练习拳击,互相切磋!',
    '篮球场上见,3v3约起来!',
    '足球爱好者,寻找队友!',
    '网球双打缺人,欢迎加入!',
    '滑板新手求带,一起进步!',
    '攀岩爱好者,寻找搭档!',
    '游泳技术提升中,求指导!',
    '健身房新手,寻找伙伴!',
    '夜跑爱好者,寻找跑友!',
    '瑜伽初学者,求老师指导!',
    '骑行环城,寻找队友!',
    '拳击训练,寻找陪练!',
    '篮球3v3,还差一个人!',
    '足球周末约球,欢迎加入!',
    '网球单打,寻找对手!',
    '滑板公园练习,一起进步!',
    '攀岩挑战,寻找搭档!',
    '游泳自由泳,求技术指导!',
    '健身房增肌,寻找伙伴!',
    '晨跑坚持者,寻找跑友!',
    '瑜伽进阶,寻找老师!',
    '骑行长途,寻找队友!',
    '拳击实战,寻找对手!',
    '篮球训练,寻找伙伴!',
    '足球友谊赛,欢迎参加!',
    '网球双打,寻找搭档!',
    '滑板技巧,求指导!',
    '攀岩新手,寻找老师!',
    '游泳比赛,寻找队友!',
    '健身房减脂,寻找伙伴!',
    '夜跑安全,寻找跑友!',
    '瑜伽冥想,寻找老师!',
    '骑行探险,寻找队友!',
    '拳击健身,寻找伙伴!'
  ]
  const tags = [
    ['#跑步', '#晨练'], ['#瑜伽'], ['#骑行', '#周末'], ['#健身'],
    ['#游泳', '#周末'], ['#跑步', '#马拉松'], ['#拳击'], ['#篮球'],
    ['#足球'], ['#网球'], ['#滑板'], ['#攀岩'],
    ['#游泳', '#技术'], ['#健身', '#新手'], ['#跑步', '#夜跑'], ['#瑜伽', '#初学者'],
    ['#骑行', '#环城'], ['#拳击', '#训练'], ['#篮球', '#3v3'], ['#足球', '#约球'],
    ['#网球', '#单打'], ['#滑板', '#公园'], ['#攀岩', '#挑战'], ['#游泳', '#自由泳'],
    ['#健身', '#增肌'], ['#跑步', '#晨跑'], ['#瑜伽', '#进阶'], ['#骑行', '#长途'],
    ['#拳击', '#实战'], ['#篮球', '#训练'], ['#足球', '#友谊赛'], ['#网球', '#双打'],
    ['#滑板', '#技巧'], ['#攀岩', '#新手'], ['#游泳', '#比赛'], ['#健身', '#减脂'],
    ['#跑步', '#夜跑'], ['#瑜伽', '#冥想'], ['#骑行', '#探险'], ['#拳击', '#健身']
  ]
  const locations = [
    '体育中心', '公园', '健身房', '游泳馆', '篮球场', '足球场', '网球场', '攀岩馆',
    '滑板公园', '羽毛球馆', '乒乓球室', '太极广场', '拳击俱乐部', '登山步道',
    '滑雪场', '体操馆', '举重室', '跳水馆', '田径场', '舞蹈室', '自行车道', '马拉松赛道'
  ]
  const avatars = [avatarChenyundong, avatarLiyujia, avatarWangqixing, avatarZhangjianshen, avatarZhaoyouyong, avatarLinpaobu, avatarSunquanji]

  // 生成所有素材数据
  const allBottleData = []
  const existingPositions = []

  for (let i = 0; i < names.length; i++) {
    // 生成不重叠的位置
    const position = generateNonOverlappingPosition(existingPositions, 18)
    existingPositions.push(position)

    allBottleData.push({
      id: i + 1,
      username: names[i] || `用户${i + 1}`,
      message: messages[i] || `分享运动心得 ${i + 1}`,
      avatar: avatars[i % avatars.length],
      tags: tags[i] || ['#运动'],
      distance: (Math.random() * 10 + 0.1).toFixed(1),
      timeAgo: `${Math.floor(Math.random() * 24) + 1}小时前`,
      location: locations[Math.floor(Math.random() * locations.length)],
      likes: Math.floor(Math.random() * 50) + 1,
      isLiked: Math.random() > 0.7,
      // 随机位置用于CSS动画（大幅减少位移幅度）
      randomX: (Math.random() - 0.5) * 60, // 从±150px减少到±30px
      randomY: (Math.random() - 0.5) * 60, // 从±150px减少到±30px
      randomRotate: (Math.random() - 0.5) * 8, // 从±7.5度减少到±4度
      // 使用不重叠的初始位置
      randomTop: position.top,
      randomLeft: position.left,
      randomRight: Math.random() * 80 + 10, // 10% 到 90%
      // 随机飘动幅度（减少幅度）
      floatAmplitude: Math.random() * 15 + 8, // 8px 到 23px
      floatDuration: Math.random() * 8 + 10, // 10s 到 18s
      floatDelay: Math.random() * 6, // 0s 到 6s
      // 随机移动方向
      floatDirection: Math.random() * 360, // 0度到360度
      floatPattern: Math.floor(Math.random() * 4) + 1 // 1-4种不同的移动模式
    })
  }

  // 将用户发出的瓶子转换为漂流瓶格式并加入列表
  const userBottles = sentBottles.value.map((bottle, index) => {
    // 为用户瓶子也生成不重叠的位置
    const position = generateNonOverlappingPosition(existingPositions, 18)
    existingPositions.push(position)

    return {
      id: 10000 + bottle.id, // 使用大ID避免冲突
      username: '我',
      message: bottle.content,
      avatar: avatarChenyundong, // 使用默认头像
      tags: bottle.tags || ['#运动'],
      distance: (Math.random() * 5 + 0.1).toFixed(1), // 用户瓶子距离较近
      timeAgo: getTimeAgo(bottle.createdAt),
      location: bottle.location || '未知位置',
      likes: bottle.likes || 0,
      isLiked: false,
      // 随机位置用于CSS动画（大幅减少位移幅度）
      randomX: (Math.random() - 0.5) * 60, // 从±150px减少到±30px
      randomY: (Math.random() - 0.5) * 60, // 从±150px减少到±30px
      randomRotate: (Math.random() - 0.5) * 8, // 从±7.5度减少到±4度
      // 使用不重叠的初始位置
      randomTop: position.top,
      randomLeft: position.left,
      randomRight: Math.random() * 80 + 10,
      // 随机飘动幅度（减少幅度）
      floatAmplitude: Math.random() * 15 + 8, // 8px 到 23px
      floatDuration: Math.random() * 8 + 10,
      floatDelay: Math.random() * 6,
      // 随机移动方向
      floatDirection: Math.random() * 360,
      floatPattern: Math.floor(Math.random() * 4) + 1,
      // 标记为用户瓶子
      isUserBottle: true,
      originalBottle: bottle
    }
  })

  // 合并所有瓶子数据
  const combinedBottles = [...allBottleData, ...userBottles]

  // 随机选择6-9个显示，并确保它们不重叠
  const displayCount = Math.floor(Math.random() * 4) + 6 // 6-9个
  const shuffled = combinedBottles.sort(() => 0.5 - Math.random())
  const selectedBottles = []
  const selectedPositions = []

  for (const bottle of shuffled) {
    if (selectedBottles.length >= displayCount) break

    const bottlePos = { top: bottle.randomTop, left: bottle.randomLeft }
    // 首先尝试18%的最小距离
    if (!isPositionOverlapping(bottlePos, selectedPositions, 18)) {
      selectedBottles.push(bottle)
      selectedPositions.push(bottlePos)
    } else if (selectedBottles.length < 6) {
      // 如果瓶子数量少于6个，降低距离要求到15%
      if (!isPositionOverlapping(bottlePos, selectedPositions, 15)) {
        selectedBottles.push(bottle)
        selectedPositions.push(bottlePos)
      }
    }
  }

  bottles.value = selectedBottles
}

// 计算时间差
const getTimeAgo = (date) => {
  const now = new Date()
  const diff = now - date
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(hours / 24)

  if (days > 0) {
    return `${days}天前`
  } else if (hours > 0) {
    return `${hours}小时前`
  } else {
    return '刚刚'
  }
}

// 跳转到漂流瓶页面
const goToDriftBottle = () => {
  router.push('/drift-bottle')
}

// 跳转到我的瓶子页面
const goToMyBottles = () => {
  router.push('/drift-bottle/my-bottles')
}

// 设置激活的按钮
const setActiveButton = (buttonName) => {
  activeButton.value = buttonName
}

// 显示提示框
const showToastMessage = (message, type = 'success') => {
  toastMessage.value = message
  toastType.value = type
  showToast.value = true

  // 3秒后自动隐藏
  setTimeout(() => {
    showToast.value = false
  }, 3000)
}


// 捞瓶子功能
const fishBottle = () => {
  showFishModal.value = true
  isFishing.value = true
  caughtBottle.value = null

  // 模拟捞瓶子的过程，2-4秒随机延迟
  const fishingTime = Math.random() * 2000 + 2000

  setTimeout(() => {
    // 从当前显示的漂流瓶列表中随机选择一个瓶子
    if (bottles.value.length > 0) {
      const randomIndex = Math.floor(Math.random() * bottles.value.length)
      caughtBottle.value = bottles.value[randomIndex]
    } else {
      // 如果没有瓶子，显示提示
      showToastMessage('当前没有可捞取的瓶子', 'warning')
    }
    isFishing.value = false
  }, fishingTime)
}

// 关闭捞瓶子模态框
const closeFishModal = () => {
  showFishModal.value = false
  isFishing.value = false
  caughtBottle.value = null
}

// 回复捞到的瓶子
const replyToBottle = () => {
  if (caughtBottle.value) {
    // 如果捞到的是用户自己的瓶子，不能回复
    if (caughtBottle.value.isUserBottle) {
      showToastMessage('不能回复自己的瓶子', 'warning')
      return
    }

    // 这里可以实现回复功能
    console.log('回复瓶子:', caughtBottle.value)
    showToastMessage('回复功能开发中...', 'info')
    // 可以跳转到回复页面或显示回复框
    closeFishModal()
  }
}

// 点赞捞到的瓶子
const likeBottle = () => {
  if (caughtBottle.value) {
    // 更新捞到的瓶子数据
    caughtBottle.value.isLiked = !caughtBottle.value.isLiked
    caughtBottle.value.likes += caughtBottle.value.isLiked ? 1 : -1

    // 同步更新原始瓶子列表中的数据
    const originalBottle = bottles.value.find(bottle => bottle.id === caughtBottle.value.id)
    if (originalBottle) {
      originalBottle.isLiked = caughtBottle.value.isLiked
      originalBottle.likes = caughtBottle.value.likes
    }

    // 如果捞到的是用户自己的瓶子，同步更新到store
    if (caughtBottle.value.isUserBottle && caughtBottle.value.originalBottle) {
      const storeBottle = sentBottles.value.find(bottle => bottle.id === caughtBottle.value.originalBottle.id)
      if (storeBottle) {
        storeBottle.likes = caughtBottle.value.likes
      }
    }

    console.log('点赞瓶子:', caughtBottle.value)
    showToastMessage(caughtBottle.value.isLiked ? '点赞成功！' : '取消点赞', 'success')
  }
}

// 扔瓶子功能
const throwBottle = async () => {
  if (!newBottleContent.value.trim()) {
    showToastMessage('请输入瓶子内容', 'warning')
    return
  }

  isThrowing.value = true

  try {
    // 模拟发送瓶子的过程
    await new Promise(resolve => setTimeout(resolve, 2000))

    // 使用全局状态管理添加瓶子
    const newBottle = addBottle({
      title: newBottleTitle.value,
      content: newBottleContent.value,
      tags: newBottleTags.value,
      location: newBottleLocation.value,
      mood: newBottleMood.value
    })

    console.log('瓶子已成功扔出:', newBottle)

    // 重置表单
    showThrowModal.value = false
    newBottleContent.value = ''
    newBottleTitle.value = ''
    newBottleTags.value = ''
    newBottleLocation.value = ''
    newBottleMood.value = 'happy'

    showToastMessage('瓶子已成功扔出！', 'success')
  } catch (error) {
    console.error('扔瓶子失败:', error)
    showToastMessage('扔瓶子失败，请重试', 'error')
  } finally {
    isThrowing.value = false
  }
}

// 漂流瓶相关功能
const toggleBottle = (id) => {
  expandedBottle.value = expandedBottle.value === id ? null : id
}

const toggleLike = (id) => {
  const bottle = bottles.value.find(b => b.id === id)
  if (bottle) {
    bottle.isLiked = !bottle.isLiked
    bottle.likes += bottle.isLiked ? 1 : -1
  }
}

const refreshBottles = () => {
  if (isRefreshing.value) return // 防止重复点击

  isRefreshing.value = true

  // 使用简化的CSS动画版本，确保效果正确
  animateBottlesSimple()

  // 动画完成后重置状态
  setTimeout(() => {
    isRefreshing.value = false
  }, 2500)
}

// 简化的动画版本
const animateBottlesSimple = () => {
  const bottleItems = document.querySelectorAll('.bottle-item')

  if (bottleItems.length === 0) return

  // 第一步：瓶子从右边滑出
  bottleItems.forEach((item, index) => {
    // 获取自定义属性值
    const randomY = getComputedStyle(item).getPropertyValue('--random-y').trim() || '0px'
    const randomRotate = getComputedStyle(item).getPropertyValue('--random-rotate').trim() || '0deg'
    
    item.style.transition = 'all 0.6s ease-in-out'
    item.style.transform = `translateX(100vw) translateY(${randomY}) rotate(${randomRotate})`
    item.style.opacity = '0'
  })

  // 第二步：延迟后生成新瓶子
  setTimeout(() => {
    // 临时隐藏容器，防止新瓶子闪烁
    const container = document.querySelector('.bottles-container')
    const originalVisibility = container ? container.style.visibility : ''
    if (container) {
      container.style.visibility = 'hidden'
    }

    generateRandomBottles()

    // 第三步：新瓶子从左边滑入
    setTimeout(() => {
      const newBottleItems = document.querySelectorAll('.bottle-item')

      newBottleItems.forEach((item, index) => {
        // 获取自定义属性值
        const randomY = getComputedStyle(item).getPropertyValue('--random-y').trim() || '0px'
        const randomRotate = getComputedStyle(item).getPropertyValue('--random-rotate').trim() || '0deg'
        
        // 立即设置初始位置（从左边开始），防止闪烁
        item.style.transition = 'none'
        item.style.transform = `translateX(-100vw) translateY(${randomY}) rotate(${randomRotate})`
        item.style.opacity = '0'
      })

      // 恢复容器可见性
      if (container) {
        container.style.visibility = originalVisibility
      }

      // 延迟后滑入到最终位置
      setTimeout(() => {
        newBottleItems.forEach((item, index) => {
          setTimeout(() => {
            // 获取自定义属性值
            const randomX = getComputedStyle(item).getPropertyValue('--random-x').trim() || '0px'
            const randomY = getComputedStyle(item).getPropertyValue('--random-y').trim() || '0px'
            const randomRotate = getComputedStyle(item).getPropertyValue('--random-rotate').trim() || '0deg'
            
            item.style.transition = 'all 0.8s ease-out'
            item.style.transform = `translateX(${randomX}) translateY(${randomY}) rotate(${randomRotate})`
            item.style.opacity = '1'
          }, index * 100 + 100) // 错开时间
        })
      }, 50)
    }, 10)
  }, 600)
}

// 生命周期
onMounted(() => {
  generateRandomBottles()
})
</script>

<style scoped>
.drift-bottle-app {
  min-height: 100vmin;
  box-sizing: border-box;
  background: linear-gradient(135deg, #2ECC71 0%, #27AE60 25%, #16A085 50%, #1ABC9C 75%, #2ECC71 100%);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
  position: relative;
  overflow: hidden;
}

/* 顶部导航栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 32px;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.app-logo {
  width: 18px;
  height: 18px;
}

.app-title {
  font-size: 24px;
  font-weight: 700;
  color: white;
  margin: 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  letter-spacing: 1px;
}

.header-center {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.header-actions .action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.fish-btn {
  background: rgba(52, 152, 219, 0.9);
  color: white;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.fish-btn:hover {
  background: rgba(41, 128, 185, 0.95);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
}

.throw-btn {
  background: rgba(46, 204, 113, 0.9);
  color: white;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 15px rgba(46, 204, 113, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.throw-btn:hover {
  background: rgba(39, 174, 96, 0.95);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(46, 204, 113, 0.4);
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.my-bottles {
  display: flex;
  align-items: center;
  gap: 8px;
  color: white;
  background: rgba(255, 255, 255, 0.2);
  padding: 8px 16px;
  border-radius: 20px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.bottles-icon {
  width: 18px;
  height: 18px;
}

.bottles-text {
  font-size: 14px;
}

.bottles-count {
  font-size: 14px;
  font-weight: 600;
}

.settings-icon {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

/* 主容器 */
.main-container {
  display: flex;
  min-height: calc(100vh - 73px);
  position: relative;
  z-index: 10;
}

/* 左侧边栏 */
.left-sidebar {
  width: 220px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(15px);
  padding: 32px 20px;
  display: flex;
  flex-direction: column;
  gap: 40px;
  border-right: 1px solid rgba(255, 255, 255, 0.2);
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-bottom: 10px;
}

.drift-btn {
  background: rgba(255, 255, 255, 0.9);
  color: #2ECC71;
  width: 100%;
  font-weight: 600;
  font-size: 16px;
  padding: 16px 24px;
  backdrop-filter: blur(10px);
  border: 2px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.drift-btn:hover {
  background: rgba(255, 255, 255, 1);
  color: #27AE60;
  transform: translateY(-4px);
  box-shadow: 0 12px 35px rgba(0, 0, 0, 0.25);
}

.btn-icon {
  width: 16px;
  height: 16px;
}

/* 主内容区 */
.main-content {
  position: relative;
  flex: 1;
  min-height: calc(100vh - 73px);
  padding: 20px;
  overflow-y: auto;
}


/* 右侧边栏 */
.right-sidebar {
  width: 260px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(15px);
  padding: 32px 24px;
  display: flex;
  flex-direction: column;
  gap: 40px;
  border-left: 1px solid rgba(255, 255, 255, 0.2);
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}

.section-icon {
  width: 18px;
  height: 18px;
}

.section-title h2 {
  font-size: 18px;
  font-weight: 700;
  color: white;
  margin: 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.data-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.data-item {
  display: flex;
  align-items: center;
  gap: 12px;
  color: white;
  font-size: 14px;
  font-weight: 500;
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.data-item:hover {
  background: rgba(255, 255, 255, 0.25);
  transform: translateX(4px);
}

.data-icon {
  width: 16px;
  height: 16px;
}

.hot-tags .section-title h2 {
  color: white;
}

.close-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 32px;
  height: 32px;
  border: none;
  background: #ff6b6b;
  color: white;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
  transition: all 0.2s ease;
  z-index: 1000;
  font-size: 20px;
  font-weight: bold;
  line-height: 1;
  pointer-events: auto;
}

.close-btn:hover {
  background: #ff5252;
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.4);
}

</style>